const fs = require('fs');
const { get } = require('http');
const path = require('path');

class File {
  constructor(filename, name, ext, isFile, size, createTime, updateTime) {
    this.filename = filename;
    this.name = name;
    this.ext = ext;
    this.isFile = isFile;
    this.size = size;
    this.createTime = createTime;
    this.updateTime = updateTime;
  }

  static async readFile(dirname) {
    // dirname 绝对文件路径
    const stat = await fs.promises.stat(dirname);
    const name = path.basename(dirname); // 获取文件名
    const ext = path.extname(dirname); // 后缀名
    const isFile = stat.isFile();
    const size = stat.size;
    const createTime = new Date(stat.birthtime);
    const updateTime = new Date(stat.mtime);
    return new File(dirname, name, ext, isFile, size, createTime, updateTime);
  }

  async getContent(isBuffer = false) {
    if (this.isFile) {
      if (isBuffer) {
        await fs.promises.readFile(this.filename);
      } else {
        return await fs.promises.readFile(this.filename, 'utf-8');
      }
    }
    return null;
  }

  async getChildren() {
    if (this.isFile) {
      //文件不可能有子文件
      return [];
    }
    let child = await fs.promises.readdir(this.filename);
    // child 里面存着 全是 创建 File的Promise
    child = child.map((name) => {
      // this.filename 文件的绝对路径
      const childFilename = path.resolve(this.filename, name);
      return File.readFile(childFilename);
    });
    return Promise.all(child);
  }
}

async function readFile(dirname) {
  const file = await File.readFile(dirname);
  return await file.getChildren();
}

async function test() {
  const dirname = path.resolve(__dirname, './myfiles');
  const result = await readFile(dirname);
  console.log(result, 'result');
  const datas = await result[0].getChildren();
  console.log(datas, 'datas');
  const content = await datas[0].getContent();
  console.log(content, 'content');
}
test();
